#!/usr/bin/python
# -*- coding:utf-8 -*-

from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider

if __name__ == "__main__":

    # 口令
    auth_provider = PlainTextAuthProvider(username='root', password='123456')

    # 创建集群
    cluster = Cluster(contact_points=['192.168.100.104'], auth_provider=auth_provider)

    # 获取会话连接
    session = cluster.connect()

    # 创建keyspace命名为stock, keyspace相当于关系型数据库中的database/schema
    session.execute("CREATE KEYSPACE IF NOT EXISTS stock WITH REPLICATION={'class':'SimpleStrategy','replication_factor':1}")

    # 切换键空间
    session.set_keyspace('stock')

    # 创建family/table命名为users, family相当于关系型数据库中的table
    session.execute("CREATE TABLE IF NOT EXISTS users(sid text primary key,name text,age int)")

    # 向users表中添加数据
    #for id in range(1,1000):
    #    sid = str(id)
    #    session.execute("INSERT INTO users(sid,name,age) VALUES(%s,%s,%s)",(sid,'scottdu' + sid, id))

    rows = session.execute("SELECT * FROM users order by sid desc")

    for row in rows:
        print(row.sid, row.name, row.age)

    cluster.shutdown()

